// 在这里处理一条新的动态,
// 把动态存入动态库, 并给客户端发送一次实时消息
let { momentsM, userInfoM } = require( '../db' );
let informClient = require('./show');

const arr = [];


// 非常烂的设计， 但是节省时间
const repeat = data => {
  if( arr.length >= 10000 ){
    for( let i = 0; i < 5000; i++){
      arr.shift();
    }
  }
  let there = arr.indexOf(data) !== -1;
  if( there ){
    return true;
  } else {
    arr.push(data);
    return false;
  }
};


const processMoment = ( req, res ) => {
  let { openid, anonymous, giftsArr = [], content, idMan } = req.body;
  console.log(openid + idMan, '收到一次请求');

  if( repeat( openid + idMan)){
    console.log('抛弃这个请求');
    return;
  } else {

    userInfoM.get()
      .findOne( { openid } )
      .then( result => {
        let { _id,  nickname= '', sex, headimgurl } = result;
        if ( !_id ){
          return Promise.reject('找不到用户数据');
        } else {
          let moment = {
            openid,
            anonymous,
            nickname,
            headimgurl,
            sex,
            content,
            giftsArr,
            time: new Date()
          };

          momentsM.get()
            .insertOne( moment )
            .then( result => {
              let { insertedId } = result;
              // 通知 webSocket 搞事啦!!!
              informClient( 'newMoment', Object.assign( {},moment,{ _id: insertedId} ) );
            } );

        }
      } )
  }





};


module.exports = processMoment;
